<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>花火爆文</title>
    <link rel="icon" href="favicon.ico" type="image/ico">
    <meta name="keywords" content="SQL,后台模板,后台管理系统,花火HTML模板">
    <meta name="description" content="一个基于Bootstrap v3.3.7的后台管理系统的HTML模板。">
    <meta name="author" content="花火">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/materialdesignicons.min.css" rel="stylesheet">
    <link href="css/style.min.css" rel="stylesheet">
    <style>
        /* 提高特定模态框的 z-index */
        #alertModal {
            z-index: 9999 !important;
            /* 使用 !important 来确保覆盖其他样式 */
        }

        /* 设置其他模态框的 z-index 值低于告警成功模态框 */
        #confirmModal,
        #editModal {
            z-index: 1050;
            /* 默认Bootstrap模态框的 z-index 值 */
        }

        #sql-input {
            width: 50%;
            /* 根据需要调整宽度 */
        }
    </style>
</head>

<body>
    <div class="container-fluid p-t-15">

        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">新增syslog</h4>
                    </div>
                    <div class="modal-body">

                        <form action="lyear_forms_elements.html" method="post" onsubmit="return false;">
                            <div class="form-group">
                                <label for="data-name">名称</label>
                                <input class="form-control" type="text" id="data-name" placeholder="输入syslog名称...">
                            </div>

                            <div class="form-group">
                                <label for="data-id">syslogId</label>
                                <input class="form-control" type="text" id="data-id" placeholder="输入syslogId...">
                            </div>

                            <div class="form-group">
                                <label for="data-on">告警产生消息体</label>
                                <input class="form-control" type="text" id="data-on" placeholder="输入告警消除消息体...">
                            </div>
                            <div class="form-group">
                                <label for="data-off">告警消除消息体</label>
                                <input class="form-control" type="text" id="data-off" placeholder="输入告警消除消息体...">
                            </div>

                        </form>

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary">保存</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12">
                <div class="form-inline text-center">
                    <input class="form-control" type="text" id="sql-input" autocomplete="off" placeholder="输入公众号名称...">
                    <button type="button" id="execute-btn" class="btn btn-primary">执行</button>
                </div>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-body">

                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>编号</th>
                                        <th>公众号名称</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="datasource-list">
                                    <!-- 动态数据将插入此处 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

        </div>

    </div>

    <!-- 提示模态框 -->
    <div class="modal fade" id="alertModal" tabindex="-1" role="dialog" aria-labelledby="alertModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="alertModalLabel">操作提示</h4>
                </div>
                <div class="modal-body" id="alertModalBody">
                    <!-- 这里将显示具体的提示消息 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade bs-example-modal-sm" id="qrCodeModal" tabindex="-1" role="dialog"
        aria-labelledby="qrCodeModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="qrCodeModalLabel">登录二维码</h4>
                </div>
                <div class="modal-body text-center">
                    <!-- 二维码图片将被放置在这里 -->
                    <img id="qrCodeImage" src="" alt="二维码" style="max-width: 100%;">
                </div>
            </div>
        </div>
    </div>

    <!-- 弹出模态框的HTML -->
    <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel">
        <div class="modal-dialog" role="document">
            文章列表
            <div class="modal-content">
                <div class="modal-body">
                    <!-- 展示数据的地方 -->
                    <div id="modalContent"></div>
                </div>
                <!-- 模态框底部，添加提取全部大纲的按钮 -->
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" onclick="requestAllOutlines()">提取全部文章大纲</button>
                </div>
            </div>
        </div>
    </div>


    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/main.min.js"></script>
    <script type="text/javascript">
        // 全局变量来存储登录状态
        var isLoggedIn = false;

        let currentBlobUrl = null; // 用于跟踪当前的blob URL
        function fetchAndShowQRCode() {
            // 使用fetch API来处理Blob数据
            fetch("/chat/qr-code")
                .then(response => {
                    // 确保响应有效
                    if (response.ok) {
                        return response.blob(); // 提取Blob对象
                    }
                    throw new Error('Network response was not ok.');
                })
                .then(imageBlob => {
                    // 创建Blob URL
                    if (currentBlobUrl) {
                        // 如果之前存在一个Blob URL，释放它
                        URL.revokeObjectURL(currentBlobUrl);
                    }
                    currentBlobUrl = URL.createObjectURL(imageBlob);

                    // 显示二维码图片
                    $("#qrCodeImage").attr("src", currentBlobUrl);
                    $("#qrCodeModal").modal('show');
                })
                .catch(error => {
                    console.error('There has been a problem with your fetch operation:', error);
                });
        }


        // 轮询登录状态
        function pollLoginStatus() {
            var loginStatusInterval = setInterval(function () {
                $.get("/chat/status", function (data) {
                    if (data && data.status === 1) {
                        clearInterval(loginStatusInterval);
                        $("#qrCodeModal").modal('hide');
                        isLoggedIn = true; // 更新全局登录状态变量
                    } else {
                        isLoggedIn = false;
                    }
                }).fail(function (jqXHR, textStatus, errorThrown) {
                    // 处理请求失败的情况
                    console.error("请求状态检查失败: ", textStatus, errorThrown);
                    clearInterval(loginStatusInterval);
                    alert('状态检查失败，请稍后重试或联系支持。');
                });
            }, 5000); // 每5秒检查一次

            //（可选）超时机制
            var timeoutMinutes = 10; // 设置超时时间，例如10分钟
            setTimeout(function () {
                clearInterval(loginStatusInterval);
                //alert('登录超时，请重新尝试。');
            }, timeoutMinutes * 60 * 1000); // 转换为毫秒
        }

        // 更新表格函数
        function updateDataSourceTable(data) {
            var tbody = $('#datasource-list');
            tbody.empty(); // 清空现有的数据

            data.forEach(function (dataSource) {
                var row = `<tr>
                <td>${dataSource.fakeid}</td>
                <td>${dataSource.nickname}</td>
                <td>
                    <div class="btn-group">
                        <button class="btn btn-xs btn-default edit-btn" title="获取" data-id="${dataSource.fakeid}" onclick="fetchAndShowData(this.getAttribute('data-id'));">
    <i class="mdi mdi-pencil"></i>
</button>
                    </div>
                </td>
            </tr>`;
                tbody.append(row);
            });
        }


        function fetchAndShowData(dataId) {
            var payload = {
                id: dataId
            };
            var dataToSend = JSON.stringify(payload);
            // 发起后台请求
            $.ajax({
                url: '/chat/searchArticle', // 后端服务的URL
                method: 'POST',
                contentType: 'application/json',
                data: dataToSend,
                dataType: 'json',
                success: function (response) {
                    if (response.code === 200 && response.data) {
                        // 更新模态框的内容
                        var contentHtml = '<ul>';
                        response.data.forEach(function (item, index) {
                            contentHtml += '<li class="list-group-item">' + item.title +
                                ' <button type="button" class="btn btn-secondary" onclick="requestOutline(\'' + item.link + '\')">一键仿写</button></li>';
                        });
                        contentHtml += '</ul>';

                        // 将生成的列表插入到模态框的指定位置
                        $("#modalContent").html(contentHtml);
                        // 显示模态框
                        $('#editModal').modal('show');
                    } else {
                        // 处理错误或者显示一些消息
                        console.error('获取数据失败:', response.msg);
                    }
                },
                error: function (xhr, status, error) {
                    // 处理错误情况
                    console.error("An error occurred: " + error);
                }
            });
        }




        // 定义在登录后获取数据的函数
        function fetchDataAfterLogin() {
            var wName = $('#sql-input').val().trim();
            var payload = {
                name: wName
            };
            var dataToSend = JSON.stringify(payload);
            console.log("Sending data:", dataToSend);
            // 发送 POST 请求到后端的 /searchAuthor 接口
            $.ajax({
                url: "/chat/searchAuthor",
                type: "post",
                contentType: 'application/json',
                data: dataToSend,
                dataType: 'json',
                success: function (response) {
                    // 处理获取到的数据
                    if (response.code === 200 && response.data) {
                        updateDataSourceTable(response.data);
                    } else {
                        // 处理错误或者显示一些消息
                        console.error('获取数据失败:', response.msg);
                    }
                },
                error: function (xhr, status, error) {
                    alert('数据获取失败，请稍后重试。');
                }
            });
        }


        $(document).ready(function () {
            // 绑定“执行”按钮的点击事件
            $("#execute-btn").click(function () {
                // 根据登录状态变量，判断下一步操作
                if (isLoggedIn) {
                    // 已登录状态，执行其他接口请求
                    fetchDataAfterLogin();

                } else {
                    // 未登录状态，展示二维码供用户扫描
                    fetchAndShowQRCode();
                    // 开始轮询登录状态
                    pollLoginStatus();
                }
            });
        });


    </script>

</body>

</html>